package com.jsh.erp.service.supplierGroup;

import com.alibaba.fastjson.JSONObject;
import com.jsh.erp.constants.BusinessConstants;
import com.jsh.erp.constants.ExceptionConstants;
import com.jsh.erp.datasource.entities.Material;
import com.jsh.erp.datasource.entities.SupplierGroup;
import com.jsh.erp.datasource.entities.SupplierGroupExample;
import com.jsh.erp.datasource.entities.User;
import com.jsh.erp.datasource.mappers.SupplierGroupMapper;
import com.jsh.erp.datasource.mappers.SupplierGroupMapperEx;
import com.jsh.erp.datasource.mappers.MaterialMapperEx;
import com.jsh.erp.datasource.vo.TreeNode;
import com.jsh.erp.exception.BusinessRunTimeException;
import com.jsh.erp.exception.JshException;
import com.jsh.erp.service.log.LogService;
import com.jsh.erp.service.user.UserService;
import com.jsh.erp.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class SupplierGroupService {
    private Logger logger = LoggerFactory.getLogger(SupplierGroupService.class);

    @Resource
    private SupplierGroupMapper supplierGroupMapper;
    @Resource
    private SupplierGroupMapperEx supplierGroupMapperEx;
    @Resource
    private UserService userService;
    @Resource
    private LogService logService;
    @Resource
    private MaterialMapperEx materialMapperEx;

    public SupplierGroup getSupplierGroup(long id)throws Exception {
        SupplierGroup result=null;
        try{
            result=supplierGroupMapper.selectByPrimaryKey(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    public List<SupplierGroup> getSupplierGroupListByIds(String ids)throws Exception {
        List<Long> idList = StringUtil.strToLongList(ids);
        List<SupplierGroup> list = new ArrayList<>();
        try{
            SupplierGroupExample example = new SupplierGroupExample();
            example.createCriteria().andIdIn(idList);
            list = supplierGroupMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<SupplierGroup> getSupplierGroup()throws Exception {
        SupplierGroupExample example = new SupplierGroupExample();
        List<SupplierGroup> list=null;
        try{
            list=supplierGroupMapper.selectByExample(example);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<SupplierGroup> getAllList(Long parentId)throws Exception {
        List<SupplierGroup> list=null;
        try{
            list = getMCList(parentId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public List<SupplierGroup> getMCList(Long parentId)throws Exception {
        List<SupplierGroup> res= new ArrayList<SupplierGroup>();
        List<SupplierGroup> list=null;
        SupplierGroupExample example = new SupplierGroupExample();
        example.createCriteria().andParentIdEqualTo(parentId).andIdNotEqualTo(1L);
        example.setOrderByClause("id");
        list=supplierGroupMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            res.addAll(list);
            for(SupplierGroup mc : list) {
                List<SupplierGroup> mcList = getMCList(mc.getId());
                if(mcList!=null && mcList.size()>0) {
                    res.addAll(mcList);
                }
            }
        }
        return res;
    }

    public List<SupplierGroup> select(String name, Integer parentId, int offset, int rows) throws Exception{
        List<SupplierGroup> list=null;
        try{
            list=supplierGroupMapperEx.selectByConditionSupplierGroup(name, parentId, offset, rows);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return list;
    }

    public Long countSupplierGroup(String name, Integer parentId) throws Exception{
        Long result=null;
        try{
            result=supplierGroupMapperEx.countsBySupplierGroup(name, parentId);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int insertSupplierGroup(JSONObject obj, HttpServletRequest request)throws Exception {
        SupplierGroup supplierGroup = JSONObject.parseObject(obj.toJSONString(), SupplierGroup.class);
        supplierGroup.setCreateTime(new Date());
        supplierGroup.setUpdateTime(new Date());
        int result=0;
        try{
            result=supplierGroupMapper.insertSelective(supplierGroup);
            logService.insertLog("商品类型",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(supplierGroup.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int updateSupplierGroup(JSONObject obj, HttpServletRequest request) throws Exception{
        SupplierGroup supplierGroup = JSONObject.parseObject(obj.toJSONString(), SupplierGroup.class);
        supplierGroup.setUpdateTime(new Date());
        int result=0;
        try{
            result=supplierGroupMapper.updateByPrimaryKeySelective(supplierGroup);
            logService.insertLog("商品类型",
                    new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(supplierGroup.getName()).toString(), request);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int deleteSupplierGroup(Long id, HttpServletRequest request)throws Exception {
        return batchDeleteSupplierGroupByIds(id.toString());
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteSupplierGroup(String ids, HttpServletRequest request)throws Exception {
        return batchDeleteSupplierGroupByIds(ids);
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int batchDeleteSupplierGroupByIds(String ids) throws Exception {
        int result=0;
        String [] idArray=ids.split(",");
        //校验产品表	jsh_material
        List<Material> materialList=null;
        try{
            materialList= materialMapperEx.getMaterialListByCategoryIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(materialList!=null&&materialList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,CategoryIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        //校验产品类型表	jsh_material_category
        List<SupplierGroup> supplierGroupList=null;
        try{
            supplierGroupList= supplierGroupMapperEx.getSupplierGroupListByCategoryIds(idArray);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(supplierGroupList!=null&&supplierGroupList.size()>0){
            logger.error("异常码[{}],异常提示[{}],参数,CategoryIds[{}]",
                    ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,ExceptionConstants.DELETE_FORCE_CONFIRM_MSG,ids);
            throw new BusinessRunTimeException(ExceptionConstants.DELETE_FORCE_CONFIRM_CODE,
                    ExceptionConstants.DELETE_FORCE_CONFIRM_MSG);
        }
        StringBuffer sb = new StringBuffer();
        sb.append(BusinessConstants.LOG_OPERATION_TYPE_DELETE);
        List<SupplierGroup> list = getSupplierGroupListByIds(ids);
        for(SupplierGroup supplierGroup: list){
            sb.append("[").append(supplierGroup.getName()).append("]");
        }
        logService.insertLog("商品类型", sb.toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        //更新时间
        Date updateDate =new Date();
        //更新人
        User userInfo=userService.getCurrentUser();
        Long updater=userInfo==null?null:userInfo.getId();
        String strArray[]=ids.split(",");
        if(strArray.length<1){
            return 0;
        }
        try{
            result=supplierGroupMapperEx.batchDeleteSupplierGroupByIds(updateDate,updater,strArray);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    public int checkIsNameExist(Long id, String name)throws Exception {
        return 0;
    }

    public List<SupplierGroup> findById(Long id)throws Exception {
        List<SupplierGroup> list=null;
        if(id!=null) {
            SupplierGroupExample example = new SupplierGroupExample();
            example.createCriteria().andIdEqualTo(id);
            try{
                list=supplierGroupMapper.selectByExample(example);
            }catch(Exception e){
                JshException.readFail(logger, e);
            }
        }
        return list;
    }
    /**
     * create by: cjl
     * description:
     *获取商品类别树数据
     * create time: 2019/2/19 14:30
     * @Param:
     * @return java.util.List<com.jsh.erp.datasource.vo.TreeNode>
     */
    public List<TreeNode> getSupplierGroupTree(Long id) throws Exception{
        List<TreeNode> list=null;
        try{
            list=supplierGroupMapperEx.getNodeTree(id);
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
       return list;
    }
    /**
     * create by: cjl
     * description:
     *  新增商品类别信息
     * create time: 2019/2/19 16:30
     * @Param: mc
     * @return void
     */
    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int addSupplierGroup(SupplierGroup mc) throws Exception {
        logService.insertLog("商品类型",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_ADD).append(mc.getName()).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        if(mc==null){
            return 0;
        }
        if(mc.getParentId()==null){
            //没有给定父级目录的id，默认设置父级目录为根目录的父目录
            mc.setParentId(BusinessConstants.MATERIAL_CATEGORY_ROOT_PARENT_ID);
        }
        //检查商品类型编号是否已存在
        checkSupplierGroupSerialNo(mc);
        //数据状态新增时默认设置为启用
        Date date=new Date();
        User userInfo=userService.getCurrentUser();
        //创建时间
        mc.setCreateTime(date);
        //更新时间
        mc.setUpdateTime(date);
        int result=0;
        try{
            result=supplierGroupMapperEx.addSupplierGroup(mc);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }

    @Transactional(value = "transactionManager", rollbackFor = Exception.class)
    public int editSupplierGroup(SupplierGroup mc) throws Exception{
        logService.insertLog("商品类型",
                new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_EDIT).append(mc.getName()).toString(),
                ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
        if(mc.getParentId()==null){
            //没有给定父级目录的id，默认设置父级目录为根目录的父目录
            mc.setParentId(BusinessConstants.MATERIAL_CATEGORY_ROOT_PARENT_ID);
        }
        //检查商品类型编号是否已存在
        checkSupplierGroupSerialNo(mc);
        //更新时间
        mc.setUpdateTime(new Date());
        //更新人
        User userInfo=userService.getCurrentUser();
        int result=0;
        try{
            result= supplierGroupMapperEx.editSupplierGroup(mc);
        }catch(Exception e){
            JshException.writeFail(logger, e);
        }
        return result;
    }
    /**
     * 根据商品类别编号判断商品类别是否已存在
     * */
    public void  checkSupplierGroupSerialNo(SupplierGroup mc)throws Exception {
        if(mc==null){
            return;
        }
        if(StringUtil.isEmpty(mc.getSNo())){
            return;
        }
        //根据商品类别编号查询商品类别
        List<SupplierGroup> mList=null;
        try{
            mList= supplierGroupMapperEx.getSupplierGroupBySerialNo(mc.getSNo(), mc.getId());
        }catch(Exception e){
            JshException.readFail(logger, e);
        }
        if(mList==null||mList.size()<1){
            //未查询到对应数据，编号可用
            return;
        }
        if(mList.size()>1){
            //查询到的数据条数大于1，编号已存在
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_CODE,
                    ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG);
        }
        if(mc.getId()==null){
            //新增时，编号已存在
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_CODE,
                    ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG);
        }
        /**
         * 包装类型用equals来比较
         * */
        if(mc.getId().equals(mList.get(0).getId())){
            //修改时，相同编号，id不同
            throw new BusinessRunTimeException(ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_CODE,
                    ExceptionConstants.MATERIAL_CATEGORY_SERIAL_ALREADY_EXISTS_MSG);
        }
    }

    /**
     * 根据名称获取类型
     * @param name
     */
    public Long getCategoryIdByName(String name){
        Long categoryId = 0L;
        SupplierGroupExample example = new SupplierGroupExample();
        example.createCriteria().andNameEqualTo(name).andDeleteFlagNotEqualTo(BusinessConstants.DELETE_FLAG_DELETED);
        List<SupplierGroup> list = supplierGroupMapper.selectByExample(example);
        if(list!=null && list.size()>0) {
            categoryId = list.get(0).getId();
        }
        return categoryId;
    }
}
